package yhao.infra.web.controller;

import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartException;
import yhao.infra.apilist.JsonCommonCodeEnum;
import yhao.infra.apilist.RequestResultException;

import javax.annotation.Resource;

import static yhao.infra.apilist.JsonCommonCodeEnum.E0020;

/**
 * @author yoara
 * <p> Created on 2019/3/28 </p>
 */
@RestController
@ControllerAdvice
public class ExceptionProcess extends BaseController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private Environment env;

    @ExceptionHandler(MultipartException.class)
    public String multipartException(MultipartException t){
        return withCustomMessage(
                "系统限制最大上传尺寸为"+env.getProperty("spring.http.multipart.max-file-size"),E0020);
    }

    /**
     * 全局的异常处理
     */
    @ExceptionHandler({Exception.class})
    public String exception(Exception e) {
        log.error("Controller 错误信息:" + e.getMessage(), e);
        if(e instanceof HystrixRuntimeException && e.getMessage().contains("timed-out")){
            return wrong(JsonCommonCodeEnum.E0018);
        }
        return wrong(JsonCommonCodeEnum.E0005);
    }

    /**
     * 全局的异常处理
     */
    @ExceptionHandler({RequestResultException.class})
    public String requestResultException(RequestResultException e) {
        log.error("remote 错误信息:" + e.getMessage(), e);
        if(e.getCode()!=null){
            return withCustomMessage(e.getMessage(),e.getCode());
        }
        String msg = e.getMessage();
        if(StringUtils.isNotEmpty(msg)&&
                (msg.contains("yhao.") || msg.contains("springframework."))){
            msg = "系统处理异常，请稍后再试";
        }
        String code = e.getCode()!=null?e.getCode():JsonCommonCodeEnum.E0001.getStatus();
        return withCustomMessage(msg,code);
    }

    /**
     * 校验的异常处理
     */
    @ExceptionHandler({BindException.class})
    public String validException1(BindException e) {
        return withCustomMessage(e.getAllErrors().get(0).getDefaultMessage(),JsonCommonCodeEnum.E0002);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public String validException2(MethodArgumentNotValidException e) {
        return withCustomMessage(
                e.getBindingResult().getAllErrors().get(0).getDefaultMessage(),JsonCommonCodeEnum.E0002);
    }
}